package com.example.his.controller;

import com.example.his.entity.Patient;
import com.example.his.mapper.PatientMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**定义RESTful API 接口
 */
//允许跨域访问@CrossOrigin
//rest(资源的表示层状态)控制器，返回资源数据,增删改查的
@CrossOrigin
@RestController
//@RequestMapping("/api/patient")
public class PatientController {
    //(由容器自动实现)依赖注入
    @Autowired
    PatientMapper mapper;
    //RESTful API -资源表示层状态迁移，接收请求返回数据
    //GET       '/api/patient'      检索实体集合
    //POST      '/api/patient'      创建一个实体
    //GET       '/api/patient/id'   检索一个实体
    //PUT       '/api/patient/id'   更新一个实体，按照Id更新
    //DELETE    '/api/patient/id'   删除一个实体

    //GET,检索实体集合
    @GetMapping("/api/patient")
    public ResponseEntity<List<Patient>> findAllPatient(){
        List<Patient> list= mapper.findAll();
        return new ResponseEntity<List<Patient>>(
            list, HttpStatus.OK);
    }
    
    //GET,根据id查找
    @GetMapping("/api/patient/{id}")
    public ResponseEntity<Patient> findPatientById(@PathVariable  int id){
        Patient patient= mapper.load(id);
        return new ResponseEntity<Patient>(
            patient,HttpStatus.OK);
    }
    //POST,创建一个实体
    @PostMapping("/api/patient")
    public ResponseEntity<Patient> add_patient(@RequestBody Patient patient){
        //持久化参数对象
        //在save之前是没有id的
        mapper.save(patient);
        //save后生成了id
        return new ResponseEntity<Patient>(
                patient,HttpStatus.OK
        );
    }
    //PUT,更新一个实体，按照Id更新
    @PutMapping("/api/patient/{id}")
    public ResponseEntity<Patient> update(@PathVariable int id,@RequestBody Patient patient){
        patient.setId(id);
        mapper.update(patient);
        return new ResponseEntity<Patient>(patient,HttpStatus.OK);
    }
    //DELETE,删除一个实体
    @DeleteMapping("/api/patient/{id}")
    public ResponseEntity<String> delete(@PathVariable int id){
        mapper.remove(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }





}
